package com.hmo.appshop;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.AbsoluteSizeSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import androidx.core.content.FileProvider;
import androidx.fragment.app.FragmentActivity;
import androidx.leanback.widget.ArrayObjectAdapter;
import androidx.leanback.widget.FocusHighlightHelper;
import androidx.leanback.widget.ItemBridgeAdapter;
import androidx.leanback.widget.VerticalGridView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cunoraz.gifview.library.GifView;
import com.hmo.http.BaseRequest;
import com.hmo.http.JsonResponseCallBack;
import com.hmo.http.ServiceEnum;

import net.dongliu.apk.parser.ApkFile;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Locale;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/*
 * Main Activity class that loads {@link MainFragment}.
 */
public class MainActivity extends FragmentActivity implements View.OnFocusChangeListener {

    public static final String TAG="MainActivity";
    public static ArrayList<AppBean> appBean0;
    public static ArrayList<AppBean> appBean1;
    public static ArrayList<AppBean> appBean2;
    VerticalGridView gridView;
    ArrayObjectAdapter data;
    RadioGroup mRadio;
    private static RadioButton button1,button2,button3;
    private static int flag=R.id.button1;
    GifView gifView;
    DialogBack dialogBack;
    interface DialogBack{
        void callInit();
    }

    @SuppressLint("RestrictedApi")
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction()==KeyEvent.ACTION_UP){
            int keyCode = event.getKeyCode();
            if (keyCode==KeyEvent.KEYCODE_BACK){
                //Log.d(TAG,"back");
                CloseDialog closeDialog = new CloseDialog();
                closeDialog.show(getSupportFragmentManager(),"closeDialog");
                return true;
            }
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mRadio = findViewById(R.id.m_radio);
        //mRadio.setOnCheckedChangeListener(this);

        button1 = findViewById(R.id.button1);
        button2 = findViewById(R.id.button2);
        button3 = findViewById(R.id.button3);

        button3.setOnFocusChangeListener(this);
        button2.setOnFocusChangeListener(this);
        button1.setOnFocusChangeListener(this);

        appBean0 = new ArrayList<>();
        appBean1 = new ArrayList<>();
        appBean2 = new ArrayList<>();

        button1.requestFocus();
        button1.setChecked(true);


        gifView = findViewById(R.id.gifView);


        loadView();
        initData();
        permission();
        dialogBack = new DialogBack() {
            @Override
            public void callInit() {
                initData();
            }
        };
        getVersion();
    }

    private void getVersion() {
        new BaseRequest().backJson(ServiceEnum.getNewVersion, new JsonResponseCallBack() {
            @Override
            public void requestFailure(int errorCode, String errMsg) {

            }

            @Override
            public void requestSuccess(final JSONObject data) {
                final JSONObject jsonObject = data.getJSONObject("data");
                final String string = jsonObject.getString("name");
                String path = getBaseContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath()+ File.separator+"appShop";
                File fPath = new File(path);
                if (!fPath.exists()){
                    fPath.mkdirs();
                }
                final File file = new File(path,string);
                if (file.exists()) {
                    try {
                        ApkFile apkFile = new ApkFile(file);

                        UpDataDialog message = new UpDataDialog(jsonObject.getString("message"), new DialogBack() {
                            @Override
                            public void callInit() {
                                installApk(file);
                            }
                        });
                        message.show(getSupportFragmentManager(),"UpData");
                    } catch (IOException e) {
                        file.delete();
                        return;
                    }
                    return;
                }
                new BaseRequest().download(string, null, new Callback() {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) {

                    }

                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                        InputStream is = null;
                        byte[] buf = new byte[2048];
                        int len = 0;
                        FileOutputStream fos = null;
                        try {

                            is = response.body().byteStream();

                            fos = new FileOutputStream(file);
                            while ((len = is.read(buf)) != -1) {
                                fos.write(buf, 0, len);
                            }
                            fos.flush();
                            UpDataDialog message = new UpDataDialog(jsonObject.getString("message"), new DialogBack() {
                                @Override
                                public void callInit() {
                                    installApk(file);
                                }
                            });
                            message.show(getSupportFragmentManager(),"UpData");
                        } catch (Exception e) {
                            is.close();
                            fos.close();
                            fos.getFD().sync();
                            file.delete();
                        }finally {

                            try {
                                if (is != null) {
                                    is.close();
                                }
                                if (fos != null) {
                                    fos.close();
                                }
                            } catch (IOException e) {

                            }
                            response.close();
                            call.cancel();
                        }
                    }
                });

            }
        });
    }

    private void loadView() {
        gridView = findViewById(R.id.grid_view);

        gridView.setNumColumns(5);
        gridView.setDuplicateParentStateEnabled(true);

//        gridView.setOnChildViewHolderSelectedListener(new OnChildViewHolderSelectedListener() {
//            @Override
//            public void onChildViewHolderSelected(RecyclerView parent, RecyclerView.ViewHolder child, int position, int subposition) {
//                super.onChildViewHolderSelected(parent, child, position, subposition);
//                Log.d(TAG, "onChildViewHolderSelected() returned: " + position);
//                //大部分情况下可以通过该方法获取到position
//            }
//
//            @Override
//            public void onChildViewHolderSelectedAndPositioned(RecyclerView parent, RecyclerView.ViewHolder child, int position, int subposition) {
//                super.onChildViewHolderSelectedAndPositioned(parent, child, position, subposition);
//                Log.d(TAG, "onChildViewHolderSelectedAndPositioned() returned: " + position);
//                //当通过setSelectedPosition()方法大幅移动列表时，该方法会回调，返回的是最终的真实的position（当set的值超出范围时...)
//            }
//        });

        GridItemPresenter gridItemPresenter = new GridItemPresenter(this.getApplicationContext(),gridView);

        data = new ArrayObjectAdapter(gridItemPresenter);
        ItemBridgeAdapter itemBridgeAdapter = new ItemBridgeAdapter(data);

        gridView.setAdapter(itemBridgeAdapter);
        FocusHighlightHelper.setupHeaderItemFocusHighlight(itemBridgeAdapter);
    }

    private void initData() {
        gifView.setVisibility(View.VISIBLE);
        appBean0.clear();
        appBean1.clear();
        appBean2.clear();
        final String size="大小：";
        final String version=" | 版本号：";
        final String postData=" | 更新时间：";
        final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
        new BaseRequest().backJson(ServiceEnum.getAppByType0, new JsonResponseCallBack() {
            @Override
            public void requestFailure(int errorCode, String errMsg) {
                Log.d(TAG, errMsg);
                LoadingDialog loadingDialog = new LoadingDialog(errMsg,dialogBack);
                loadingDialog.show(getSupportFragmentManager(),"appType0");
            }

            @Override
            public void requestSuccess(JSONObject d) {
                JSONArray data = d.getJSONArray("data");
                for (int i = 0; i< data.size(); i++){
                    JSONObject jsonObject = data.getJSONObject(i);
                    AppBean appBean = new AppBean();
                    appBean.setId(i);
                    appBean.setApk(jsonObject.getString("apk"));
                    appBean.setName(jsonObject.getString("name"));
                    appBean.setParam(size+jsonObject.getString("size")+version+jsonObject.getString("version")+postData+dateFormat.format(jsonObject.get("postdate")));
                    appBean.setAbout(jsonObject.getString("description"));
                    String pictures = jsonObject.getString("pictures");
                    if (pictures!=null)
                        appBean.setPicture(pictures.split("\\|"));
                    appBean.setLogoName(jsonObject.getString("logo"));
                    appBean.setType(jsonObject.getIntValue("type"));
                    appBean0.add(appBean);
                }
                MainActivity.this.data.addAll(0,appBean0);
                new BaseRequest().backBitmaps(MainActivity.this.data);

                if (button1.isChecked()){
                    gifView.setVisibility(View.INVISIBLE);
                }
            }
        });
        new BaseRequest().backJson(ServiceEnum.getAppByType1, new JsonResponseCallBack() {
            @Override
            public void requestFailure(int errorCode, String errMsg) {
                Log.d(TAG, errMsg);
            }

            @Override
            public void requestSuccess(JSONObject d) {
                JSONArray data = d.getJSONArray("data");
                for (int i=0;i<data.size();i++){
                    JSONObject jsonObject = data.getJSONObject(i);
                    AppBean appBean = new AppBean();
                    appBean.setId(i);
                    appBean.setApk(jsonObject.getString("apk"));
                    appBean.setName(jsonObject.getString("name"));
                    appBean.setParam(size+jsonObject.getString("size")+version+jsonObject.getString("version")+postData+dateFormat.format(jsonObject.get("postdate")));
                    appBean.setAbout(jsonObject.getString("description"));
                    String pictures = jsonObject.getString("pictures");
                    if (pictures!=null)
                        appBean.setPicture(pictures.split("\\|"));
                    appBean.setLogoName(jsonObject.getString("logo"));
                    appBean.setType(jsonObject.getIntValue("type"));
                    appBean1.add(appBean);
                }
                new BaseRequest().backBitmaps(appBean1);
                if (button2.isChecked()){
                    gifView.setVisibility(View.INVISIBLE);
                }
            }
        });
        new BaseRequest().backJson(ServiceEnum.getAppByType2, new JsonResponseCallBack() {
            @Override
            public void requestFailure(int errorCode, String errMsg) {
                Log.d(TAG, errMsg);
            }

            @Override
            public void requestSuccess(JSONObject d) {
                JSONArray data = d.getJSONArray("data");
                for (int i=0;i<data.size();i++){
                    JSONObject jsonObject = data.getJSONObject(i);
                    AppBean appBean = new AppBean();
                    appBean.setId(i);
                    appBean.setApk(jsonObject.getString("apk"));
                    appBean.setName(jsonObject.getString("name"));
                    appBean.setParam(size+jsonObject.getString("size")+version+jsonObject.getString("version")+postData+dateFormat.format(jsonObject.get("postdate")));
                    appBean.setAbout(jsonObject.getString("description"));
                    String pictures = jsonObject.getString("pictures");
                    if (pictures!=null)
                        appBean.setPicture(pictures.split("\\|"));
                    appBean.setLogoName(jsonObject.getString("logo"));
                    appBean.setType(jsonObject.getIntValue("type"));
                    appBean2.add(appBean);
                }
                new BaseRequest().backBitmaps(appBean2);
                if (button3.isChecked()){
                    gifView.setVisibility(View.INVISIBLE);
                }
            }
        });
    }


    public static SpannableString spannable(String s){
        SpannableString sp = new SpannableString("应用简介："+s);
        sp.setSpan(new AbsoluteSizeSpan(30,true),0,5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return sp;
    }

    @Override
    public void onFocusChange(View view, boolean b) {
        if (!b|| flag==view.getId()){
            //Log.d(TAG,""+b);
            return;
        }
        switch (view.getId()) {
            case R.id.button1:
                flag=R.id.button1;
                if (data == null) {

                    break;
                }

                if (appBean0.size()==0){
                    gifView.setVisibility(View.VISIBLE);
                }else gifView.setVisibility(View.INVISIBLE);

                data.clear();
                data.addAll(0, appBean0);
                break;
            case R.id.button2:
                flag=R.id.button2;

                if (appBean1.size()==0){
                    gifView.setVisibility(View.VISIBLE);
                }else gifView.setVisibility(View.INVISIBLE);

                data.clear();
                data.addAll(0, appBean1);
                break;
            case R.id.button3:
                flag=R.id.button3;

                if (appBean2.size()==0){
                    gifView.setVisibility(View.VISIBLE);
                }else gifView.setVisibility(View.INVISIBLE);

                data.clear();
                data.addAll(0, appBean2);
                break;
        }
        RadioButton button = (RadioButton) view;
        button.setChecked(true);
    }


    public static void setRadioFocues(){
        if (flag==R.id.button1){
            button1.requestFocus();
        }else if (flag==R.id.button2){
            button2.requestFocus();
        }else {
            button3.requestFocus();
        }
    }

    private void permission(){
        if (Build.VERSION.SDK_INT >= 23) {
            int REQUEST_CODE_CONTACT = 101;
            String[] permissions = {
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE};
            //验证是否许可权限
            for (String str : permissions) {
                if (MainActivity.this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    MainActivity.this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                    return;
                } else {
                    //这里就是权限打开之后自己要操作的逻辑
                }
            }
        }
    }

    private void installApk(File apk){
        Intent intent = new Intent(Intent.ACTION_VIEW);

        Uri contentUri = FileProvider.getUriForFile(getBaseContext(), getApplication().getPackageName()+".fileprovider", apk);

        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        }
        intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        this.startActivityForResult(intent, 0);
    }
}
